import React, { useState, useEffect } from 'react';
import { Card, Form, Input, Upload, Button, Radio, Row, Col, message, Progress } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import {to} from 'await-to-js';
import { postToOss, generateAIVideo, getPercent } from '@/api/AIVideo';
const { TextArea } = Input;

const AiVideo: React.FC = () => {
  const [form] = Form.useForm();
  const [videoScript, setVideoScript] = useState<string>('');
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [uploading, setUploading] = useState<boolean>(false);
  const [generating, setGenerating] = useState<boolean>(false);
  const [progress, setProgress] = useState<number>(0);
  const [jobId, setJobId] = useState<string>('');
  const [intervalId, setIntervalId] = useState<NodeJS.Timeout | null>(null);
  const [videoUrl, setVideoUrl] = useState<string>('');
  const [messageShown, setMessageShown] = useState<boolean>(false);

  // 轮询获取生成进度
  const startPolling = (id: string) => {
    // 清除可能存在的旧计时器
    if (intervalId) {
      clearInterval(intervalId);
      setIntervalId(null);
    }
    
    // 重置消息状态和进度
    setMessageShown(false);
    setProgress(0);
    setVideoUrl('');
    
    // 创建新的轮询计时器
    const newIntervalId = setInterval(async () => {
      // 如果已经有视频URL，说明已经完成，停止轮询
      if (videoUrl) {
        console.log('检测到视频URL已存在，停止轮询');
        stopPolling();
        return;
      }
      
      const [err, res] = await to(getPercent(id));
      if (err) {
        message.error('获取生成进度失败');
        stopPolling();
        return;
      }
      
      if (res && res.data) {
        try {
          // 解析返回的数据
          let responseObj;
          if (typeof res.data === 'string') {
            responseObj = JSON.parse(res.data);
          } else {
            responseObj = res.data;
          }
          
          // 检查错误信息
          if (responseObj.error_code !== 0) {
            message.error(`获取进度失败: ${responseObj.error_msg || '未知错误'}`);
            stopPolling();
            return;
          }
          
          // 检查是否视频生成完毕
          if (responseObj.data && responseObj.data.statusCode === "1" && responseObj.data.videoAddr) {
            // 视频已生成完成，有下载地址
            console.log('视频生成完成，获取到URL:', responseObj.data.videoAddr);
            setVideoUrl(responseObj.data.videoAddr);
            setProgress(100);
            
            // 仅当消息未显示过时才显示
            if (!messageShown) {
              message.success('视频生成完成！可以下载了');
              setMessageShown(true);
            }
            
            // 确保停止轮询
            setTimeout(() => {
              stopPolling();
            }, 100);
            
            return;
          }
          
          // 获取进度值并转换为百分比
          if (responseObj.data && typeof responseObj.data.progress === 'number') {
            // 将小数进度值转换为百分比整数 (例如：0.25 → 25)
            const percent = Math.round(responseObj.data.progress * 100);
            setProgress(percent);
          }
        } catch (parseError) {
          console.error('解析进度数据失败:', parseError, res.data);
          message.error('解析进度数据时出错');
          stopPolling();
        }
      }
    }, 3000); // 每2秒轮询一次
    
    setIntervalId(newIntervalId);
  };
  
  // 停止轮询 - 增强版
  const stopPolling = () => {
    console.log('执行停止轮询函数');
    if (intervalId) {
      console.log('清除定时器:', intervalId);
      clearInterval(intervalId);
      setIntervalId(null);
    }
    setGenerating(false);
  };
  
  // 增强组件卸载时的清理
  useEffect(() => {
    return () => {
      if (intervalId) {
        console.log('组件卸载，清除定时器');
        clearInterval(intervalId);
      }
    };
  }, [intervalId]);
  
  // 监听videoUrl变化，确保生成完成后停止轮询
  useEffect(() => {
    if (videoUrl && generating) {
      console.log('检测到视频URL已设置且正在生成中，停止轮询');
      stopPolling();
    }
  }, [videoUrl, generating]);

  const handleScriptChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setVideoScript(e.target.value);
  };

  // 修改上传处理函数，记录和验证文件状态
  const handleUploadChange = ({ fileList }: { fileList: UploadFile[] }) => {
    console.log('文件列表变化:', fileList.map(f => ({ name: f.name, size: f.size, status: f.status })));
    setFileList(fileList);
  };

  // 修改上传单个图片函数，确保正确创建FormData
  const uploadSingleImage = async (file: File, retryCount = 0): Promise<string | null> => {
    try {
      // 每次创建新的FormData对象
      const formData = new FormData();
      formData.append('file', file);
      
      console.log(`开始上传图片: ${file.name}, 大小: ${(file.size / 1024).toFixed(2)}KB, 类型: ${file.type}`);
      
      // 确保请求headers正确
      const [err, res] = await to(postToOss(formData));
      
      if (err) {
        console.error(`图片 ${file.name} 上传失败:`, err);
        // 如果失败且未超过最大重试次数，则重试
        if (retryCount < 4) {
          console.log(`重试上传图片: ${file.name}, 第${retryCount + 1}次...`);
          return await uploadSingleImage(file, retryCount + 1);
        }
        message.error(`图片 ${file.name} 上传失败，已重试${retryCount}次`);
        return null;
      }
      
      if (!res?.data?.url) {
        console.error(`图片 ${file.name} 上传成功但无URL:`, res);
        return null;
      }
      
      console.log(`图片 ${file.name} 上传成功: ${res.data.url}`);
      return res.data.url;
    } catch (error) {
      console.error(`图片 ${file.name} 上传异常:`, error);
      return null;
    }
  };

  // 重写提交处理函数，确保所有文件正确处理
  const handleSubmit = async (values: any) => {
    try {
      setUploading(true);
      
      // 更严格地验证和提取文件
      const files: File[] = [];
      
      console.log('开始处理文件列表, 总数:', fileList.length);
      fileList.forEach((item, index) => {
        if (item.originFileObj) {
          console.log(`文件 ${index+1}: ${item.name}, 有效, 大小: ${item.size}`);
          files.push(item.originFileObj);
        } else {
          console.warn(`文件 ${index+1}: ${item.name}, 无效, 无originFileObj`);
        }
      });
      
      if (files.length === 0) {
        message.error('请至少上传一张有效图片');
        setUploading(false);
        return;
      }
      
      console.log(`准备上传 ${files.length} 张图片`);
      message.loading(`准备上传 ${files.length} 张图片...`, 0);
      
      // 逐个上传图片而不是使用Promise.all，以确保每个图片都被处理
      const imgUrlList: string[] = [];
      for (let i = 0; i < files.length; i++) {
        message.destroy();
        message.loading(`正在上传第 ${i + 1}/${files.length} 张图片...`, 0);
        console.log(`开始上传第 ${i + 1}/${files.length} 张图片`);
        
        const url = await uploadSingleImage(files[i]);
        if (url) {
          imgUrlList.push(url);
          console.log(`第 ${i + 1} 张图片上传成功`);
        } else {
          console.error(`第 ${i + 1} 张图片上传失败`);
        }
      }
      
      message.destroy();
      
      // 过滤出成功上传的图片URL
      console.log(`成功上传 ${imgUrlList.length}/${files.length} 张图片`);
      
      if (imgUrlList.length === 0) {
        message.error('所有图片上传失败');
        setUploading(false);
        return;
      }
      
      if (imgUrlList.length < files.length) {
        message.warning(`有 ${files.length - imgUrlList.length} 张图片上传失败，将使用已成功上传的 ${imgUrlList.length} 张图片继续`);
      } else {
        message.success(`已成功上传所有 ${files.length} 张图片`);
      }
      
      // 继续生成视频的流程
      message.loading('正在生成视频...', 0);
      
      // 获取分辨率
      let resolution = '[1280,720]'; // 默认横版
      if (values.orientation === 'vertical') {
        resolution = '[720,1280]'; // 竖版
      }
      
      const [err, res] = await to(generateAIVideo({
        text: videoScript,
        resolution: resolution,
        imgUrlList: imgUrlList
      }));
      
      message.destroy(); // 清除loading消息
      
      if (err) {
        message.error('视频生成失败，请稍后重试');
      } else {
        // 解析JSON字符串响应
        try {
          let responseObj;
          if (typeof res.data === 'string') {
            responseObj = JSON.parse(res.data);
          } else {
            responseObj = res.data;
          }
          
          // 检查是否有错误信息
          if (responseObj.error_msg) {
            message.error(`生成视频失败: ${responseObj.error_msg}`);
          } else if (responseObj.data && (responseObj.data.jobId || responseObj.data.id)) {
            // 获取jobId (可能在data.jobId或data.id中)
            const id = responseObj.data.id;
            console.log('生成视频的jobId:', id,responseObj);
            setJobId(id.toString());
            setGenerating(true);
            setProgress(0);
            message.success('视频生成请求已提交，正在处理中...');
            
            // 开始轮询进度
            startPolling(id.toString());
          } else {
            message.warning('视频已提交但无法获取进度信息');
          }
        } catch (parseError) {
          console.error('解析响应数据失败:', parseError, res.data);
          message.error('处理响应数据时出错');
        }
      }
    } catch (error) {
      console.error('生成视频出错:', error);
      message.error('系统错误，请稍后重试');
    } finally {
      setUploading(false);
    }
  };

  // 下载视频函数
  const handleDownloadVideo = () => {
    if (!videoUrl) {
      message.error('没有可下载的视频');
      return;
    }
    
    // 创建一个隐藏的a标签来触发下载
    const link = document.createElement('a');
    link.href = videoUrl;
    link.target = '_blank';
    link.download = `AI视频_${new Date().getTime()}.mp4`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // 页面样式
  const styles = {
    container: {
      padding: '24px',
    },
    row: {
      minHeight: '70vh',
    },
    card: {
      height: '100%',
      display: 'flex',
      flexDirection: 'column' as 'column',
    },
    textAreaContainer: {
      flex: 1,
      display: 'flex',
      flexDirection: 'column' as 'column',
      overflow: 'hidden', // 防止内容溢出
    },
    textArea: {
      flex: 1,
      resize: 'none',
      // 移除固定的minHeight设置
    },
    formContainer: {
      display: 'flex',
      flexDirection: 'column' as 'column',
    }
  };

  return (
    <div style={styles.container}>
      <Row gutter={24} style={styles.row}>
        {/* 左侧文案输入区域 */}
        <Col span={16}>
          <Card title="视频文案" style={styles.card} bodyStyle={styles.textAreaContainer}>
            <TextArea
              placeholder="请在此输入视频文案内容..."
              value={videoScript}
              onChange={handleScriptChange}
              style={styles.textArea}
              disabled={generating || uploading}
            />
          </Card>
        </Col>

        {/* 右侧表单配置区域 */}
        <Col span={8}>
          <Card title="视频配置" style={styles.card}>
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
              initialValues={{ orientation: 'horizontal' }}
              style={styles.formContainer}
              disabled={generating || uploading}
            >
              <Form.Item
                label="视频素材"
                name="images"
                valuePropName="fileList"
                getValueFromEvent={e => e && e.fileList}
                rules={[{ required: true, message: '请上传视频素材图片' }]}
              >
                <Upload
                  listType="picture-card"
                  fileList={fileList}
                  onChange={handleUploadChange}
                  beforeUpload={() => false}
                  multiple
                >
                  {fileList.length < 8 && (
                    <div>
                      <UploadOutlined />
                      <div style={{ marginTop: 8 }}>上传图片</div>
                    </div>
                  )}
                </Upload>
              </Form.Item>

              <Form.Item
                label="视频方向"
                name="orientation"
                rules={[{ required: true, message: '请选择视频方向' }]}
              >
                <Radio.Group>
                  <Radio value="horizontal">横版</Radio>
                  <Radio value="vertical">竖版</Radio>
                </Radio.Group>
              </Form.Item>

              {generating && (
                <div style={{ marginBottom: '20px' }}>
                  <div style={{ marginBottom: '8px' }}>视频生成进度:</div>
                  <Progress percent={progress} status={videoUrl ? "success" : "active"} />
                </div>
              )}

              {videoUrl && (
                <Form.Item>
                  <Button 
                    type="primary" 
                    onClick={handleDownloadVideo}
                    block
                    style={{ marginBottom: '16px' }}
                    disabled={!videoUrl}
                  >
                    下载生成的视频
                  </Button>
                </Form.Item>
              )}

              <Form.Item style={{ marginTop: 'auto' }}>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  block
                  loading={uploading}
                  disabled={uploading || generating}
                >
                  {uploading ? '处理中...' : generating ? `生成中(${progress}%)` : '生成视频'}
                </Button>
              </Form.Item>
            </Form>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default AiVideo;